var path = require('path');
var webpack = require('webpack');
var glob = require('glob');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');

//var ExtractTextPluginCss = new ExtractTextPlugin('./target/static/styles/[name].css');
var webpackConfig = {
	// src 路径
	srcPath: './src/',	
}
module.exports = {
	// 入口文件，通过解析该文件获取所有项目相关资源
	entry : getEntries('**/index.js'),
	// 打包输出文件
	output : {
		path : path.resolve(__dirname, './' + process.env.NODE_ENV),
		publicPath : process.env.NODE_ENV === 'production' ? "../" : '/' + process.env.NODE_ENV,
		// filename: 'build.js'
		filename : 'script/[name]-[hash].js'
	},
	module : {
		rules : [
			// 对vue文件做处理
			{
				test : /\.vue$/,
				loader : 'vue-loader',
				options : {
					loaders : {
						// Since sass-loader (weirdly) has SCSS as its
						// default parse mode, we map
						// the "scss" and "sass" values for the lang
						// attribute to the right configs here.
						// other preprocessors should work out of the box,
						// no loader config like this necessary.
//						 css: ExtractTextPlugin.extract("css"),
						'scss' : 'vue-style-loader!css-loader!sass-loader',
						'sass' : 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
					}
				// other vue-loader options go here
				}
			}, 
			// 对js文件做处理
			{
				test : /\.js$/,
				loader : 'babel-loader',
				exclude : /node_modules/
			}, 
			// 处理css文件
			{
	            test: /\.css$/,
	            use: ExtractTextPlugin.extract({
            		fallback: 'style-loader', 
            		use: 'css-loader',
            	}),
	        },
			// 对图片文件进行打包，小于8K的文件Base64编码嵌入文件中
			{
	        	test: /\.((woff2?|svg)(\?v=[0-9]\.[0-9]\.[0-9]))|(woff2?|svg|jpe?g|png|gif|ico)$/,
	        	loader : 'url-loader',
				options : {
					limit: 8192,
					// 暂时先将所有的图片放置在common/images下，并使用hash标注在文件名中，放置文件名重复
					name: './images/[name]-[hash].[ext]',
				}
			},
			// 字体文件装在
			{
                test: /\.((ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9]))|(ttf|eot)$/,
                loader: 'url-loader',
                options: {
                	limit: 8192,
					// 暂时先将所有的图片放置在common/fonts下，并使用hash标注在文件名中，放置文件名重复
                	name: './fonts/[name]-[hash].[ext]',
                }
            },
		]
	},
	plugins: [
//	    new webpack.HotModuleReplacementPlugin(),
//	    new webpack.NoEmitOnErrorsPlugin(),
		// 将所有的css都定义为公共css，放在style.css中
		new ExtractTextPlugin({
			filename: 'styles/general.css',
			allChunks: true,
			disable: false
		}),
		// 提取公共js到common.js
//		new webpack.optimize.CommonsChunkPlugin('common.js'),
		// 使用ProvidePlugin加载使用频率高的模块
        new webpack.ProvidePlugin({
            $: "webpack-zepto"
        }),
	],
	resolve : {
		alias : {
			'vue$' : 'vue/dist/vue.common.js'
		}
	},
	devServer : {
//		contentBase: "target/",
		historyApiFallback : true,
//		hot: true,
//		inline: true,
		noInfo : true
	},
	performance : {
		hints : false
	},
	devtool : '#eval-source-map'
}

// 生成对应的html文件
var htmlPages = getEntries('**/*.html');
for(var page in htmlPages) {
	var conf = {
//			alwaysWriteToDisk: true,
		filename: "pages/" + page + ".html",
		template: htmlPages[page],
		inject: true,
		minify: {
			// 在生产环境最小化
//			removeComments: true,
//		    collapseWhitespace: true,
//		    removeAttributeQuotes: true
		},
		// necessary to consistently work with multiple chunks via CommonsChunkPlugin
		chunksSortMode: 'dependency'
	};
	if (page in module.exports.entry) {
	    conf.chunks = ['manifest', 'vendor', page];
	    conf.hash = true;
	}
	module.exports.plugins.push(new HtmlWebpackPlugin(conf));
}

if (process.env.NODE_ENV === 'production') {
	module.exports.devtool = '#source-map'
	// http://vue-loader.vuejs.org/en/workflow/production.html
	module.exports.plugins = (module.exports.plugins || []).concat([
			new webpack.DefinePlugin({
				'process.env' : {
					NODE_ENV : '"production"'
				}
			}), new webpack.optimize.UglifyJsPlugin({
				sourceMap : true,
				compress : {
					warnings : false
				}
			}), new webpack.LoaderOptionsPlugin({
				minimize : true
			}) ])
}

/**
 * 根据通配符获取文件
 * @param globpath
 * @returns
 */
function getEntries(globpath) {
	globpath = webpackConfig.srcPath + globpath;
	var entries = {},
    basename, tmp, pathname;

	glob.sync(globpath).forEach(function (entry) {
	    basename = path.basename(entry, path.extname(entry));
	    dirname = path.dirname(entry);
	    pathname = dirname.substr(webpackConfig.srcPath.length) + "/" + basename;
	    // entryName 只取模块的第一层目录。和html模板保持一致
	    entryName = pathname.substr(0, pathname.indexOf("/"));
	    entries[entryName] = entry;
	});
	return entries;
}
